package com.example.controller;

import com.example.entity.SysUser;
import com.example.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/auth")
@CrossOrigin(origins = "*")
public class AuthController {

    @Autowired
    private AuthService authService;

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody Map<String, String> loginRequest) {
        String username = loginRequest.get("username");
        String password = loginRequest.get("password");
        String roleId = loginRequest.get("roleId");
        
        try {
            // 调用服务层进行身份验证
            SysUser user = authService.authenticate(username, password, roleId);
            
            // 生成简单的token（实际项目中应使用JWT或其他安全机制）
            String token = generateToken(user);
            
            // 构建响应数据
            Map<String, Object> response = new HashMap<>();
            response.put("token", token);
            
            // 构建用户信息（不包含敏感数据如密码）
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("id", user.getId());
            userInfo.put("name", user.getName());
            userInfo.put("jobNumber", user.getJobNumber());
            userInfo.put("phone", user.getPhone());
            userInfo.put("roleId", user.getRoleId());
            
            response.put("userInfo", userInfo);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        }
    }
    
    // 简单的token生成方法（实际项目中应使用更安全的方式）
    private String generateToken(SysUser user) {
        return user.getId() + "_" + System.currentTimeMillis();
    }
}